package com.gupao.javavip.netty.push.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.apachecommons.CommonsLog;
import org.msgpack.MessagePack;

import java.util.List;

@CommonsLog
public abstract class AbstractMessagePackDecoder<T> extends ByteToMessageDecoder {
    private MessagePack messagePack = new MessagePack();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //先获取可读字节数
        int length = in.readableBytes();
        if (length <= 0) {
            return;
        }

        byte[] array = new byte[length];
        in.getBytes(in.readerIndex(), array, 0, length);

        try {
            T obj = decodeByMessagePack(messagePack, array);
            out.add(obj);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        in.clear();
    }

    protected abstract T decodeByMessagePack(MessagePack messagePack, byte[] array) throws java.io.IOException;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("与客户端断开连接:" + cause.getMessage(), cause);
        ctx.close();
    }
}
